package utils

import (
	"fmt"
	"github.com/jinzhu/now"
	"time"
)

// 秒数格式化
func SecondFormat(second int) (h, m, s int) {
	h = second / 3600
	m = second % 3600 / 60
	s = second % 60

	return h, m, s
}

// 补零
func AddZero(num int) string {
	if num < 10 {
		return fmt.Sprintf("0%d", num)
	}
	return fmt.Sprintf("%d", num)
}

// 创建日期数组 间隔小时
func CreateDays(startTime, endTime, format string, intervalHour int) (dayList []string) {
	if intervalHour <= 0 {
		intervalHour = 1
	}

	dayTime := 60 * 60 * intervalHour
	timeOff := true
	var targetT time.Time
	t1, _ := time.ParseInLocation("2006-01-02 15:04:05", startTime, time.Local)
	t2, _ := time.ParseInLocation("2006-01-02 15:04:05", endTime, time.Local)

	for timeOff {
		if targetT.Unix() <= t2.Unix() {
			targetT = time.Unix(t1.Unix()+int64(dayTime*len(dayList)), 0)
			if targetT.Unix() >= t2.Unix() {
				if t2.Format(format) != dayList[len(dayList)-1] {
					dayList = append(dayList, t2.Format(format))
				}
			} else {
				dayList = append(dayList, targetT.Format(format))
			}
		} else {
			timeOff = false
		}
	}

	return dayList
}

// 计算间隔天数
func GetDayLen(startTime, endTime string) (dayLen int) {
	t1, _ := time.ParseInLocation("2006-01-02 15:04:05", startTime, time.Local)
	t2, _ := time.ParseInLocation("2006-01-02 15:04:05", endTime, time.Local)

	dayLen = int(t2.Unix()-t1.Unix()) / int(60*60*24)
	if dayLen <= 0 {
		dayLen = 1
	}

	return dayLen
}

func AddDate(t time.Time, years int, months int) time.Time {
	year, month, day := t.Date()
	hour, min, sec := t.Clock()

	tm := month + time.Month(months)
	firstDayOfMonthAfterAddDate := time.Date(year+years, tm, 1, hour, min, sec, t.Nanosecond(), t.Location())
	lastDay := now.New(firstDayOfMonthAfterAddDate).EndOfMonth().Day()

	if day > lastDay {
		day = lastDay
	}

	return time.Date(year+years, month+time.Month(months), day, hour, min, sec, t.Nanosecond(), t.Location())
}
